<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="材料抽检" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
        class="u-sticky"
      ></xmInfo>
    </u-sticky>
    <view class="cu-card">
      <scroll-view
        scroll-y="true"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :scrolltolower-enabled="true"
        :refresher-triggered="triggered"
        @refresherrefresh="refresherrefresh"
        @scrolltoupper="refresherrefresh"
        class="scroll-view-class"
        :style="{ height: computedScrollViewHeight }"
      >
        <view
          class="scroll-content"
          ref="scrollContent"
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
          :style="{ height: computedScrollViewHeight }"
        >
          <view
            class="cu-item shadow"
            
            v-for="(item, index) in list"
            :key="index"
          >
            <view class="cu-form-group align-center justify-start">
              <view class="title">
                <view
                  style="
                    display: inline-block;
                    padding: 5px;
                    background: #3e97b0;
                    color: #fff;
                    width: 40px;
                    text-align: center;
                    font-style: italic;
                    font-weight: bold;
                  "
                >
                  {{ index + 1 }}
                </view>
              </view>
              <view class="flex align-center justify-between flex-sub">
                <view class="flex">
                  {{ item.checkdate || "" }}
                </view>
                <view class="flex"
                  ><dictLabel
                    :value="item.status"
                    dict-type="bpm_biz_status"
                    :dict-list="bizList"
                  ></dictLabel
                ></view>
              </view>
            </view>

            <view class="cu-form-group justify-start">
              <view class="title">结果</view>
              <view>
                <dictLabel
                  :value="item.state"
                  dict-type="zf_material_check_status"
                  :dict-list="dictList"
                ></dictLabel>
              </view>
            </view>
            <view class="cu-form-group justify-start">
              <view class="title">抽检人</view>
              <view>{{ item.checker || "" }}</view>
            </view>
            <view class="cu-form-group justify-start">
              <view class="title">审核人</view>
              <view>
                {{ item.reviewer || ""
                }}{{ item.reviewdate ? "(" + item.reviewdate + ")" : "" }}</view
              >
            </view>
            <view class="cu-form-group justify-start">
              <view class="title">处理人</view>
              <view>
                {{ item.dealwithper || ""
                }}{{
                  item.dealwithdate ? "(" + item.dealwithdate + ")" : ""
                }}</view
              >
            </view>
            <view class="cu-form-group justify-start">
              <view class="title">处理结果</view>
              <view> {{ item.dealwithresult || "" }}</view>
            </view>
            <view
              class="cu-form-group"
              style="color: #3e97b0"
			  v-if="item.bdeal&&dealflag"
            >
              <view class="content-footer-right" ></view>
              <view class="justify-end">
                <button
                  class="cu-btn lines-green shadow-blur"
                  @click="bhgClick(item.id)"
                  
                >
                  <text class="cuIcon-add"></text>不合格材料处理
                </button>
              </view>
            </view>
			
			<view
			  class="cu-form-group"
			  style="color: #3e97b0"
			  
			>
				<view class="content-footer-right">
					<view v-if="item.status == '4' || item.status == '5' || item.status == '6'"  @click="handleBpmMyTask({id:item.id})"><u-icon name="checkmark-circle"></u-icon>任务办理</view>
				</view>
				<view @click="add(item.id,item.status)">
					查看详情<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			
			
          </view>

          <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
          <view v-if="list.length" class="loadmore">
            <u-loadmore :status="loadStatus"></u-loadmore>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="btn-group cu-bar foot" v-if="addflag">
      <button :disabled="projStatus=='1' || projStatus=='2' || projStatus=='3'?false:true" class="cu-btn bg-green shadow-blur" @tap="add()">
        <text class="cuIcon-add"></text> 创建
      </button>
    </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo, dictLabel },
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
      list: [],
      itemContent: {},
      query: {
        pageNo: 1,
        pageSize: 20,
        // orderBy: "a.create_date desc",
      },
      loadStatus: "loadmore",
      triggered: false,
      scrollViewHeight: 0,
      headerHeight: 0,
      dictList: [],
      bizList: [],
      addflag:hasPermission('app:btn:add:cailiaochoujian'),
      dealflag:hasPermission('app:btn:check:pmMaterialcheck:del'),
	  projStatus:this.$store.state.auth.projStatus,
    };
  },
  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        this.query.projectname = this.itemContent.projectname;
        console.log(this.itemContent);

        // this.loadData();
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
    this.getDictList();
  },
  onShow() {
    this.query.pageNo = 1;
    this.loadData();
  },
  mounted() {
    this.$refs.xmInfo.$on("child-mounted-done", () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === "auto"
        ? "auto"
        : `${this.scrollViewHeight}px`;
    },
  },
  methods: {
	  handleBpmMyTask(record){
	  	this.$u.api.bpm.bpmTaskDeForm({ formKey: 'material_check', bizKey: record.id }).then((res) => {
	  	  if(res.result == 'true'){
	  		  const url = res.mobileUrl;
	  		  if (url && url != '') {
	  		  	uni.navigateTo({
	  		  		url: url
	  		  	})
	  		  }
	  	  }else{
	  		this.$u.toast(res.message);
	  	  }
	  	});
	  },
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    bhgClick(id){
      const xm = {
          projectno: this.itemContent.projectno,
          projectname: this.itemContent.projectname,
        };
      uni.navigateTo({
        url: `/pages/zfgs/material/check/pmMaterialcheck/bhgForm?id=${id}&xm=${JSON.stringify(xm)}`,
      });
    },
    getDictList() {
      this.$u.api
        .dictListData({ dictType: "zf_material_check_status" })
        .then((res) => {
          this.dictList = res;
        });
      this.$u.api.dictListData({ dictType: "bpm_biz_status" }).then((res) => {
        this.bizList = res;
      });
    },
    async calculateScrollViewHeight() {
      try {
        // 等待头部高度计算完成
        await new Promise((resolve) => {
          this.$nextTick(() => {
            this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
          });
        });
        // 计算tabBar高度
        if(this.addflag){
          this.tabBarHeight = 70; // 假设tabbar高度为50px，实际应根据实际情况获取
        }else{
          this.tabBarHeight = 0; // 假设tabbar高度为50px，实际应根据实际情况获取
        }

        // 获取屏幕高度
        const systemInfo = uni.getSystemInfoSync();
        const screenHeight = systemInfo.windowHeight;

        // 计算scroll-view高度
        this.scrollViewHeight =
          screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error("Error while calculating ScrollView height:", error);
      }
    },
    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
      // 循环10次重复赋值
      this.$u.api.zfgs.checkPmMaterialcheckListData(this.query).then((res) => {
        if (res.list.length >= 0) {
          // this.xmList = res.list
          if (res.list.length < 20 || res.list.length == 0) {
            this.loadStatus = "nomore";
          }
          var data = res.list;
          //模拟收藏

          if (type == "add") {
            for (var i = 0; i < data.length; i++) {
              this.list.push(data[i]);
            }
          } else {
            this.list = data;
          }
        }
      });
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      setTimeout(() => {
        this.triggered = false;
      }, 500);
      // this.triggered = false;
    },
    add(id,status) {
      

      if (!!id) {
        if(status==5){
          uni.navigateTo({
            url: "/pages/zfgs/material/check/pmMaterialcheck/form?id=" + id,
          });
        }else{
          uni.navigateTo({
            url: "/pages/zfgs/material/check/pmMaterialcheck/readOnlyForm?id=" + id,
          });
        }
        
      } else {
        const xm = {
          projectno: this.itemContent.projectno,
          projectname: this.itemContent.projectname,
        };
        console.log(xm,'xm');
        uni.navigateTo({
          url:
            "/pages/zfgs/material/check/pmMaterialcheck/form?xm=" +
            JSON.stringify(xm),
        });
      }
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
      this.$refs.xmInfo.$off("child-mounted-done");
    } catch (e) {
      console.log("Error while unbinding event:", e);
    }
  },
};
</script>
<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
// .line-green{
//   border: 1px solid #39b54a;
//   border-radius: 10rpx;
// }
.title {
  width: 200rpx;
}
</style>